let stickywidth = 220
  , stickyheight = 200
  , max_notes = 1e4
  , allowed_tags = "<br /><br><ol></ol><ul></ul><li></li><strong></strong><i></i>"
  , html5sticky = {};
const STICKYNOTES_ALLKEYS = "stickynotes|allkeys"
  , STICKYNOTES_FOLDERS = "stickynotes|folders"
  , STICKYNOTES_SELECTED_FOLDER = "stickynotes|selected|folder";
html5sticky.addNote = function() {
    if ($(".note_common").length === max_notes)
        return html5sticky.showMessage("#FFE16B", "black", "当前便签笔记已经足够多了，不能再添加了！"),
        !1;
    let t = "stickynote_" + 1 * new Date
      , e = getDateTime()
      , o = new Date
      , l = html5sticky.getColor()
      , i = html5sticky.getCurrentFolder()[1]
      , n = $('<div class="note_common ' + l + '" />').appendTo($("#main"));
    html5sticky.addPin(n),
    $(n).append($("<h2>" + e + "</h2>")),
    $(n).append($("<p></p>")),
    $(n).append($('<span id="idf_' + t + '" />')),
    $(".note_common").css({
        width: stickywidth + "px",
        height: stickyheight + "px"
    }),
    $(".note_common p").css({
        height: stickyheight - 60 + "px",
        width: stickywidth + 9 + "px"
    }),
    $("html, body").animate({
        scrollTop: $(n).offset().top
    });
    let s = (localStorage.getItem(STICKYNOTES_ALLKEYS) || "").split(",");
    s.push(t + "|text"),
    s.push(t + "|bgcolor"),
    s.push(t + "|dated"),
    s.push(t + "|folderid"),
    localStorage.setItem(STICKYNOTES_ALLKEYS, s.join(",")),
    localStorage.setItem(t + "|text", $(n).find("h2").text() + "|" + $(n).find("p").text()),
    localStorage.setItem(t + "|bgcolor", l),
    localStorage.setItem(t + "|dated", e + "|" + getISODateTime(o)),
    localStorage.setItem(t + "|folderid", i),
    html5sticky.enlargeNote(n),
    html5sticky.updateNotesCountForFolder()
}
,
html5sticky.saveNote = function(t) {
    let e = html5sticky.getIdentifier($(t))
      , o = html5sticky.stripTags($(t).closest(".bignote").find(".hedit")[0].value, allowed_tags)
      , l = html5sticky.stripTags($(t).closest(".bignote").find(".pedit")[0].value, allowed_tags);
    l = l.replace(/\r?\n/g, "<br />"),
    localStorage.setItem(e + "|text", o + "|" + l);
    let i = $("[id^=idf_" + e + "]").closest(".note_common");
    i.find("h2").text(o),
    i.find("p").html(l);
    let n = localStorage.getItem(e + "|folderid") || 0
      , s = $(t).closest(".bignote").find(".fedit")[0].value;
    localStorage.setItem(e + "|folderid", s),
    html5sticky.closeNote(t),
    html5sticky.showMessage("#9BED87", "black", "笔记保存成功！"),
    String(n) !== String(s) && (i.fadeOut("slow", function() {
        i.remove(),
        !$(".note_common").length > 0 && $("#removenotes").slideUp("slow")
    }),
    html5sticky.updateNotesCountForFolder())
}
,
html5sticky.updateNotesCountForFolder = function() {
    let t = (localStorage.getItem(STICKYNOTES_ALLKEYS) || "").split(",")
      , e = html5sticky.loadFolders();
    Object.keys(e).forEach(o=>{
        let l = t.filter(t=>/\|folderid/.test(t) && String(e[o]) === (localStorage.getItem(t) || "0")).length;
        $("#f_" + e[o]).find("i").text("(" + l + ")")
    }
    )
}
,
html5sticky.getIdentifier = function(t) {
    if (!t)
        return "stickynote_" + (1 * new Date + Math.floor(10 * Math.random()));
    let e = $(t).closest(".bignote").find("[id^=idf_]").attr("id");
    return void 0 !== e && null != e || (e = $(t).closest(".note_common").find("[id^=idf_]").attr("id")),
    void 0 !== e && (e = e.replace("idf_", ""))
}
,
html5sticky.deleteNoteById = function(t) {
    localStorage.removeItem(t),
    localStorage.removeItem(t + "|text"),
    localStorage.removeItem(t + "|bgcolor"),
    localStorage.removeItem(t + "|dated"),
    localStorage.removeItem(t + "|folderid");
    let e = (localStorage.getItem(STICKYNOTES_ALLKEYS) || "").split(",");
    ["text", "bgcolor", "dated", "folderid"].forEach(function(o) {
        let l = t + "|" + o;
        e.indexOf(l) > -1 && e.splice(e.indexOf(l), 1)
    }),
    localStorage.setItem(STICKYNOTES_ALLKEYS, e.join(","))
}
,
html5sticky.deleteNote = function(t) {
    if (confirm("确定要删除这个便签笔记吗，一旦删除则不可恢复，请三思?")) {
        let e = html5sticky.getIdentifier($(t));
        html5sticky.deleteNoteById(e),
        $(t).closest(".note_common").fadeOut("slow", function() {
            $(t).closest(".note_common").remove()
        })
    }
}
,
html5sticky.deleteAllNotes = function() {
    confirm("建议删除之前先【全部导出】，否则一旦删除则不可恢复，请三思?") && $(".note_common").fadeOut("slow", function() {
        $(".note_common").remove(),
        (localStorage.getItem(STICKYNOTES_ALLKEYS) || "").split(",").forEach(function(t) {
            localStorage.removeItem(t)
        }),
        localStorage.removeItem(STICKYNOTES_ALLKEYS),
        html5sticky.deleteAllFolders(),
        location.reload(!0)
    })
}
,
html5sticky.closeNote = function(t) {
    $(t).closest(".bignote")[html5sticky.getAnimation(!0)]("slow", function() {
        $("#overlay").remove()
    })
}
,
html5sticky.editNote = function(t, e) {
    let o = t.find("p").html();
    o = o.replace(/(<br \/>|<br>)/g, "\n"),
    t.find("p").replaceWith('<textarea class="pedit" placeholder="在这里添加笔记" />'),
    t.find(".pedit").val(o).css({
        marginTop: "5px",
        resize: "none",
        outline: "none"
    }).addClass("inset").width("568px").height("280px");
    let l = t.find("h2").text();
    t.find("h2").replaceWith('<input type="text" class="hedit" />'),
    $(".hedit").addClass("inset").val(html5sticky.stripTags(l, allowed_tags)).width(250);
    let i = html5sticky.loadFolders()
      , n = localStorage.getItem(t.find('span[id^="idf_"]').attr("id").replace("idf_", "") + "|folderid") || "0";
    $(".hedit").after('<select class="fedit form-control">' + Object.keys(i).map(t=>`<option value="${i[t]}" ${i[t] == n ? "selected" : ""}>${t}</option>`).join("") + "</select>"),
    $('<a href="#" class="close_stickynote x-btn-min">关闭</a>').css({
        position: "absolute",
        top: 5,
        right: 5,
        color: "#000"
    }).appendTo(t),
    $('<a href="#" class="save_stickynote x-btn-min">保存</a>').css({
        position: "absolute",
        top: 5,
        right: 40,
        color: "#000"
    }).appendTo(t)
}
,
html5sticky.getNotesByFolderId = function(t) {
    let e = (localStorage.getItem(STICKYNOTES_ALLKEYS) || "").split(",")
      , o = [];
    return e.forEach(e=>{
        if (!/\|text/.test(e))
            return !1;
        let l = e.replace("|text", "")
          , i = localStorage.getItem(l + "|folderid") || "0";
        if (String(t) !== i)
            return !1;
        o.push(l)
    }
    ),
    o
}
,
html5sticky.loadNotes = function(t) {
    let e = $("#main").html("")
      , o = html5sticky.getNotesByFolderId(t);
    o.forEach(t=>{
        let o, l, i, n, s;
        l = localStorage.getItem(t + "|bgcolor"),
        i = (s = localStorage.getItem(t + "|text").split("|"))[0],
        n = s[1],
        o = $('<div class="note_common ' + l + '" />').appendTo(e),
        html5sticky.addPin(o),
        $(o).append($("<h2></h2>")),
        $(o).append($("<p></p>")),
        $(o).append($('<span id="idf_' + t + '" />')),
        $(o).find("h2").text(html5sticky.stripTags(i, allowed_tags)),
        $(o).find("p").html(html5sticky.stripTags(n, allowed_tags)),
        $(".note_common").css({
            width: stickywidth + "px",
            height: stickyheight + "px"
        }),
        $(".note_common p").css({
            height: stickyheight - 60 + "px",
            width: stickywidth - 24 + "px"
        })
    }
    ),
    $("#f_" + t).find("i").text("(" + o.length + ")")
}
,
html5sticky.collapse = function() {
    let t = parseInt($(".note_common:first").find("h2").height() || 0, 10) + "px";
    $(".note_common").animate({
        height: t
    }, function() {
        $(".note_common").find("p").hide()
    })
}
,
html5sticky.expand = function() {
    $(".note_common").animate({
        height: stickyheight
    }, function() {
        $(".note_common").find("p").fadeIn("slow")
    })
}
,
html5sticky.showMessage = function(t, e, o, l) {
    $("#smsg").is(":visible") || $("html, body").animate({
        scrollTop: 0
    }, 500, function() {
        $("#smsg").length || ($('<div id="smsg">' + o + "</div>").appendTo($("body")).css({
            position: "absolute",
            top: 0,
            left: 0,
            right: 0,
            height: "40px",
            lineHeight: "40px",
            background: t,
            color: e,
            zIndex: 1e3,
            fontWeight: "bold",
            textAlign: "center",
            opacity: .9,
            margin: "auto",
            display: "none"
        }).slideDown("show"),
        setTimeout(function() {
            $("#smsg").animate({
                width: "hide"
            }, function() {
                $("#smsg").remove(),
                l && l()
            })
        }, 2e3))
    })
}
,
html5sticky.getColor = function() {
    let t = "";
    return "stickynote" + (t += "0123456789".charAt(Math.floor(Math.random() * "0123456789".length)))
}
,
html5sticky.getAnimation = function(t) {
    let e = [];
    return void 0 !== t ? (e[1] = "hide",
    e[2] = "fadeOut",
    e[3] = "slideUp") : (e[1] = "show",
    e[2] = "fadeIn",
    e[3] = "slideDown"),
    e[Math.ceil(3 * Math.random())]
}
,
html5sticky.addPin = function(t) {
    let e = $('<div class="btn-close"><a href="#" class="delete_stickynote x-btn-min">删除</a></div>')
      , o = $(`<div align="center"><img pin-png src="${html5sticky.images["pin.png"]}" alt=""></div>`);
    $(e).css({
        position: "absolute",
        top: -15,
        right: -15
    }).hide().prependTo($(t)),
    $(o).css({
        position: "absolute",
        zIndex: 99,
        top: -15,
        left: parseInt(stickywidth / 2, 10) - 10
    }).prependTo($(t))
}
,
html5sticky.enlargeNote = function(t) {
    $this = $(t),
    $('<div id="overlay" />').css({
        position: "fixed",
        background: "rgba(0,0,0,0.5)",
        top: "0",
        left: "0",
        width: "100%",
        height: "100%",
        zIndex: "100"
    }).appendTo($("body")),
    $clone = $(t).clone().removeClass("note_common").addClass("bignote").appendTo($("#overlay")),
    $clone.find($("img[pin-png]").closest("div")).hide(),
    $($clone).css({
        position: "absolute",
        zIndex: 500,
        cursor: "default",
        paddingTop: "5px",
        width: "600px",
        height: "376px",
        top: "50%",
        left: "50%",
        display: "none",
        marginLeft: "-300px",
        marginTop: "-200px"
    }),
    $($clone)[html5sticky.getAnimation()](400);
    let e = ""
      , o = ""
      , l = html5sticky.getIdentifier($(t))
      , i = localStorage.getItem(l + "|dated")
      , n = `<img class="left" align="absmiddle" time-png src="${html5sticky.images["time.png"]}">`;
    e = i.split("|")[0],
    o = prettyDate(i.split("|")[1]),
    e = e.length > 0 ? "创建于：" + e : "",
    o = o.length > 0 ? " (" + o + ")" : "",
    n = e.length > 0 ? n : "",
    $('<div class="timeago left" />').prependTo($clone),
    $(".timeago").css({
        fontSize: "12px",
        fontFamily: "tahoma"
    }).html(n + "&nbsp;&nbsp;" + e + o).after('<div class="clear" />'),
    $($clone).find(".icons-footer").hide(),
    html5sticky.editNote($clone, t)
}
,
html5sticky.stripTags = function(t, e) {
    e = (((e || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join("");
    return t.replace(/<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi, "").replace(/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, function(t, o) {
        return e.indexOf("<" + o.toLowerCase() + ">") > -1 ? t : ""
    })
}
,
html5sticky.export = function() {
    let t = (localStorage.getItem(STICKYNOTES_ALLKEYS) || "").split(",")
      , e = null;
    t.length && (e = new JSZip);
    let o = {};
    t.forEach(t=>{
        if (!/\|text/.test(t))
            return !1;
        let l, i, n, s, a, c = t.replace("|text", "");
        if (l = localStorage.getItem(c + "|dated"),
        a = localStorage.getItem(c + "|folderid") || "0",
        !o[a]) {
            let t = html5sticky.findFolderNameById(a);
            o[a] = e.folder(t)
        }
        i = (s = localStorage.getItem(c + "|text").split("|"))[0],
        n = s[1],
        o[a].file(i + ".txt", ["# title：" + i, "# date：" + l, "# content：\n" + n].join("\n\n"))
    }
    ),
    e && e.generateAsync({
        type: "blob"
    }).then(function(t) {
        let e = document.createElement("a");
        e.style.cssText = "position:absolute;top:-1000px;left:-10000px;",
        e.setAttribute("download", "我的便签笔记-" + 1 * new Date + ".zip"),
        e.href = URL.createObjectURL(new Blob([t],{
            type: "application/octet-stream"
        })),
        document.body.appendChild(e),
        e.click()
    })
}
,
html5sticky.importNotes = function() {
    let t = function() {
        zip.useWebWorkers = !1;
        window.webkitURL || window.mozURL || window.URL;
        return {
            getEntries: function(t, e) {
                zip.createReader(new zip.BlobReader(t), function(t) {
                    t.getEntries(e)
                }, function(t) {
                    console.log(t)
                })
            },
            getEntryFile: function(t, e, o) {
                t.getData(new zip.TextWriter, function(t) {
                    e(t)
                }, o)
            }
        }
    }()
      , e = document.createElement("input");
    e.type = "file",
    e.accept = "application/zip",
    e.style.cssText = "position:absolute;top:-100px;left:-100px",
    e.addEventListener("change", function(o) {
        t.getEntries(e.files[0], function(e) {
            let o = 0
              , l = e.filter(t=>!t.directory).length;
            e.forEach(function(e) {
                if (e.directory) {
                    o++;
                    let t = e.filename.replace(/\//, "");
                    html5sticky.loadFolders()[t] || html5sticky.saveFolder(t, (new Date).getTime())
                } else
                    t.getEntryFile(e, function(t) {
                        let i = html5sticky.getIdentifier()
                          , n = t.split("# date：")[0].split("# title：")[1].trim()
                          , s = t.split("# date：")[1].split("# content：")[0].trim()
                          , a = t.split("# content：")[1].trim().replace(/\r?\n/g, "<br />")
                          , c = html5sticky.findFolderByName(e.filename.split("/")[0])
                          , d = (localStorage.getItem(STICKYNOTES_ALLKEYS) || "").split(",");
                        d.push(i + "|text"),
                        d.push(i + "|bgcolor"),
                        d.push(i + "|dated"),
                        d.push(i + "|folderid"),
                        localStorage.setItem(STICKYNOTES_ALLKEYS, d.join(",")),
                        localStorage.setItem(i + "|text", n + "|" + a),
                        localStorage.setItem(i + "|bgcolor", html5sticky.getColor()),
                        localStorage.setItem(i + "|dated", s),
                        localStorage.setItem(i + "|folderid", c),
                        ++o === l && html5sticky.showMessage("#9BED87", "black", "操作成功！共导入" + o + "条笔记！", ()=>{
                            location.reload()
                        }
                        )
                    })
            })
        })
    }, !1),
    document.body.appendChild(e),
    e.click()
}
,
html5sticky.buildFoldersAndInitNotes = function() {
    let t = html5sticky.loadFolders();
    Object.keys(t).forEach((e,o)=>{
        html5sticky.createFolder(e, t[e]),
        html5sticky.loadNotes(t[e])
    }
    );
    let e = html5sticky.getCurrentFolder()[1];
    $("li#f_" + e).length || (e = t[Object.keys(t)[0]]),
    $("li#f_" + e).addClass("x-selected"),
    html5sticky.loadNotes(e)
}
,
html5sticky.loadFolders = function() {
    let t = JSON.parse(localStorage.getItem(STICKYNOTES_FOLDERS) || "{}") || {};
    return t["默认文件夹"] || (t["默认文件夹"] = "0"),
    t
}
,
html5sticky.deleteAllFolders = function() {
    localStorage.setItem(STICKYNOTES_FOLDERS, "{}"),
    localStorage.setItem(STICKYNOTES_SELECTED_FOLDER, "[]")
}
,
html5sticky.saveFolder = function(t, e, o) {
    let l = html5sticky.loadFolders();
    t && (l[t] = e),
    o && delete l[o],
    localStorage.setItem(STICKYNOTES_FOLDERS, JSON.stringify(l))
}
,
html5sticky.createFolder = function(t, e) {
    if (t = t || window.prompt("新建文件夹")) {
        if (!e) {
            if (html5sticky.loadFolders()[t])
                return alert("你已经创建过这个文件夹！")
        }
        e = e || (new Date).getTime(),
        html5sticky.saveFolder(t, e);
        let o = $('<li><span></span><i>(0)</i><a class="btn-delete">删除</a><a class="btn-rename">重命名</a></li>').find("span").text(t).end().attr("id", "f_" + e).appendTo("#folders");
        return o.find("a.btn-rename").click(l=>{
            l.stopPropagation();
            let i = window.prompt("新的文件夹名称");
            i && i !== t && (html5sticky.saveFolder(i, e, t),
            o.find("span").text(i))
        }
        ),
        o.find("a.btn-delete").click(l=>{
            l.stopPropagation();
            let i = parseInt(o.find("i").text().replace(/\W/g, ""));
            if (i && !window.confirm("当前文件夹下包含【" + i + "】个便签，建议先将笔记挪到其他文件夹再进行删除！如果你想暴力删除，那你可以继续了！！！"))
                return !1;
            html5sticky.saveFolder(null, e, t),
            o.remove(),
            html5sticky.getNotesByFolderId(e).forEach(t=>html5sticky.deleteNoteById(t)),
            $("#main").html(""),
            html5sticky.showMessage("#9BED87", "black", "文件夹已删除成功！笔记本将重新加载！"),
            setTimeout(()=>{
                location.reload(!0)
            }
            , 2e3)
        }
        ),
        o
    }
    if (null !== t)
        return alert("文件夹名不能为空！")
}
,
html5sticky.getCurrentFolder = function() {
    let t = JSON.parse(localStorage.getItem(STICKYNOTES_SELECTED_FOLDER) || "[]") || [];
    return t.length || (t = ["默认文件夹", "0"]),
    t
}
,
html5sticky.setCurrentFolder = function(t, e) {
    localStorage.setItem(STICKYNOTES_SELECTED_FOLDER, JSON.stringify([t, e]))
}
,
html5sticky.findFolderNameById = function(t) {
    let e = html5sticky.loadFolders()
      , o = Object.keys(e).filter(o=>String(e[o]) === String(t));
    return o.length ? o[0] : "默认文件夹"
}
,
html5sticky.findFolderByName = function(t) {
    let e = JSON.parse(localStorage.getItem(STICKYNOTES_FOLDERS) || "{}") || {};
    return e["默认文件夹"] || (e["默认文件夹"] = "0"),
    e[t]
}
,
html5sticky.images = {
    "pin.png": "",
    "time.png": ""
};
